import { reqCode, reqLogin, reqLogOut,reqRegister, reqUserInfo } from "@/api"
import router from '@/router'
import { getUserTempId } from "@/utils/user"



const state = {
  userTempId: getUserTempId(),
  token: localStorage.getItem('TOKEN'),
  userInfo: {}, //存储个人信息
}

const mutations = {
  SET_TOKEN(state,token) {
    state.token = token
  },
  SET_USERINFO(state, userInfo) {
    state.userInfo = userInfo
  }
}

const actions = {
  //退出登录
  async logOut({ commit, dispatch }) {
    try {
      //调用接口是为了统治后端token失效
      await reqLogOut()
    } catch (error) {
      console.error(error);
      alert('退出登录失败')  
    } finally {
      dispatch('clearToken')
      //清楚个人信息
      commit('SET_USERINFO',{})
      //跳转首页
      router.push('/home')
    }
  },
  // 清除token
  clearToken({ commit }) {
    commit('SET_TOKEN', "") // 清除store中的token
    localStorage.removeItem('TOKEN') // 清除localStorage中的token
  },
  //获取个人信息
  async getUserInfo({commit} ) {
    try {
      let result = await reqUserInfo() 
        if (result && result.code == 200) {
          commit('SET_USERINFO',result.data)

         
        
      }
    } catch (error) {
      console.error(error);
    }
  },
  //登录
  async login ({commit}, data) {
    try {
      let result = await reqLogin(data)
      if (result && result.code == 200) {
        commit('SET_TOKEN',result.data.token)

        localStorage.setItem('TOKEN',result.data.token)
        return
      }
      return Promise.reject(result.message || '登录失败')
    } catch (error) {
      console.error(error);
      return Promise.reject(result.message || '登录失败')
    }
  },
  //注册
  async register(miniStore,data) {
    try {
      let result = await reqRegister(data) 
        if (result && result.code == 200) {
          return 'ok'
      }
      return Promise.reject(result.message || '注册失败')
    } catch (error) {
      return Promise.reject(error)
    }
  },
  //获取code
  async getCode({ commit },phone) {
    try {
      let result = await reqCode(phone)
      if (result && result.code == 200) {
        return result.data
      }
      return Promise.reject(result.message || '获取code失败')
    } catch (error) {
      return Promise.reject(error)
    }
  }
}

const getters = {}

export default  {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
}